package pe.edu.unmsm.pacis.shca.ams;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.UnreadableException;
import jade.wrapper.gateway.GatewayAgent;

import java.io.IOException;
import java.util.Map;

import org.apache.log4j.Logger;

import pe.edu.unmsm.pacis.shca.domain.message.GlobalMessage;

public class GateWay extends GatewayAgent {
	
	
	private static final long serialVersionUID = 1L;
	
	private GlobalMessage globalMsg = null;
	//private static final Logger logger = Logger.getLogger(GatewayAgent.class);
	
	protected void processCommand(java.lang.Object obj) {
			
		if (obj instanceof GlobalMessage)	{
			globalMsg = (GlobalMessage)obj;
			
			ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
			msg.addReceiver(new AID( globalMsg.getRemoteAgent(), AID.ISLOCALNAME) );
			// send POJO
			try {
				msg.setContentObject(globalMsg);
			} catch (IOException e) {
				//logger.error("IOException", e);
			}
			send(msg);
		}
		
	}

	@SuppressWarnings("serial")
	public void setup()
	{
		// Waiting for the answer
		addBehaviour(new CyclicBehaviour(this) 
		{
			@SuppressWarnings("unchecked")
			public void action() {

				ACLMessage msg = receive();
				
				if ((msg!=null)&&(globalMsg!=null))	{
					Map<String,Object> replyMap = null;
					try {
						replyMap = (Map<String,Object>)msg.getContentObject();
					} catch (UnreadableException e) {
						//logger.error("UnreadableException", e);
					}
					releaseCommand(globalMsg);
					globalMsg.setReply(replyMap);
				} else block();
			 }
		});	
		
		super.setup();
	}
	
}
